<?php
// $Id$

/**
 * Controller_User 控制器
 */
class Controller_User extends Controller_Abstract
{
    private $good_users = array();
    function actionIndex()
    {	
        if(null == $this->_app->currentUser())
        {
            return $this->_redirect(url('user/login'));
        }
        $current_user = $this->_app->currentUserObject();
        
        $blNeedModifyPassword = false;
        $total_time = 3600*24*90;
        if($current_user->reserved_2 == null)
        {
            $current_user->reserved_2 = intval(CURRENT_TIMESTAMP);
            $current_user->save();
        }

        if(intval(CURRENT_TIMESTAMP) - intval($current_user->reserved_2) > $total_time)
        {
            $blNeedModifyPassword = true;
        }

        $this->_view['blNeedModifyPassword'] = $blNeedModifyPassword;
        $this->_view['current_user'] = $current_user;
        $this->_viewname = 'Index';
    }

    function actionsearchuser()
    {
        $user_phone = $this->_context->user_phone;
        if(null == $this->_app->currentUser())
        {
            return $this->_redirect(url('user/login'));
        }
        $current_user = $this->_app->currentUserObject();
        $select = User::find('username = ?', $user_phone)->query();

        $result="";

        if(strlen($select->username)>0 && ($select->username == $user_phone))
        {
            $user_name = $select->username;
            if ($current_user->enterprise_id  == $select->enterprise_id)
            {
                if(strlen($select->user_realname) > 1)
                {
                    $result =$select->user_id."|&nbsp;&nbsp;".$user_phone.", 用户实名为：".$select->user_realname;
                }
                else
                {
                    $result =$select->user_id.'|&nbsp;&nbsp;'.$user_phone.'存在.';
                }
            }
        }
        echo $result;

        return;
    }

    function actionRequestWether()
    {
        $city = $this->_context->city;
        $city = empty($city) ? 'xian' : $city;

        $content = file_get_contents("http://www.google.com/ig/api?weather=$city&hl=zh-cn");
        //$content || die("No such city's data");
        if(!$content)
        {
            return 'failed';
        }
        $content = mb_convert_encoding($content, 'UTF-8', 'GBK');
        echo $content;
        return;
        /*
        $xml = simplexml_load_string($content);
        $date = $xml->weather->forecast_information->forecast_date->attributes();
        $html = $date. "<br>\r\n";
        $current = $xml->weather->current_conditions;
        $condition = $current->condition->attributes();
        $temp_c = $current->temp_c->attributes();
        $humidity = $current->humidity->attributes();
        $icon = $current->icon->attributes();
        $wind=$current->wind_condition->attributes();
        $icon && $icon = $xml->weather->forecast_conditions->icon->attributes();
        $html.= "当前: {$condition}, {$temp_c}°C,<img src='http://www.google.com/ig{$icon}'/> {$humidity}{$wind}<br />";
        foreach($xml->weather->forecast_conditions as $forecast) 
        {
            $low = $forecast->low->attributes();
            $high = $forecast->high->attributes();
            $icon = $forecast->icon->attributes();
            $condition = $forecast->condition->attributes();
            $day_of_week = $forecast->day_of_week->attributes();
            $html.= "{$day_of_week} : {$high} / {$low} °C, {$condition} <img src='http://www.google.com/ig{$icon}' /><br />";
        }
        //print $html;
        */
    }

    function actionRequireBanner()
    {
        $username = $this->_context->user_name;
        $user = User::find("username = $username")->getOne();
        //dump($user);
        $articles = Article::find("article_status = 4 and article_isbanner = 1 AND enterprise_id = $user->enterprise_id")->order("article_id desc")->getAll();
        //dump($articles);
        $web_site = Q::ini('appini/web_site_ip');
        
        $xml_string = '<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
    <channel>
        <title>电信</title>
        <description>测试数据这里</description>
        <link>http://www.baidu.com</link>
        <language>zh_CN</language>
        <pubDate>2012-02-17 00:02:50</pubDate>
        <lastBuildDate>2012-02-17 00:02:50</lastBuildDate>
        <generator>Wadiff RSS Generator</generator>
        <ttl>5</ttl>';
        $i = 0;
        foreach($articles as $article)
        {
            if($i >4) {break;};
            $i = $i + 1;
            $xml_string .="\n       <item>\n";
            $xml_string .= "            <title>$article->article_name</title>\n";
            $xml_string .= "            <link>$web_site$article->article_url</link>\n";
            $xml_string .= "            <description>null</description>\n";
            $xml_string .= "            <pubDate>null</pubDate>\n";
            $xml_string .= "            <icon>$article->article_icon</icon>\n";
            $xml_string .="         </item>\n";
        }
        $xml_string .= '    </channel>
</rss>';
        echo $xml_string;

        return;
    }
    
    function actionGetTopUser()
    {
        if(null == $this->_app->currentUser())
        {
            return $this->_redirect(url('default/index'));
        }
        $cur_user = $this->_app->currentUserObject();
        if($cur_user->permission_id != 2)
        {
            return $this->_redirect(url('default/index'));
        }
        
        $page = intval($this->_context->page);
        if ($page < 1) $page = 1;
        $user_num=0;
        $select = User::find('enterprise_id = ? AND login_count > ?', $cur_user->enterprise_id, Q::ini('appini/web_cfg_top_user_login_time'))->all();
        $select->limitPage($page, 10);
        // 将分页信息和查询到的数据传递到视图
        $this->_view['pagination'] = $select->getPagination();
        $this->_view['users'] = $select->getAll();

        $this->_view['current_user'] = $cur_user;

        if($select->getCount() > 10)
        {
            $this->_view['num'] = 10;
        }
        else
        {
            $this->_view['num'] = $select->getCount();
        }

        $this->_viewname = 'onlineuser';
    }

    function actionGetAllmembers()
    {
        if(null == $this->_app->currentUser())
        {
            return $this->_redirect(url('default/index'));
        }
        $cur_user = $this->_app->currentUserObject();
        if($cur_user->permission_id != 2)
        {
            return $this->_redirect(url('default/index'));
        }
        
        $page = intval($this->_context->page);
        if ($page < 1) $page = 1;
        $user_num=0;
        $select = User::find('enterprise_id = ? and permission_id <> 2', $cur_user->enterprise_id)->all();
        $select->limitPage($page, 10);
        // 将分页信息和查询到的数据传递到视图
        $this->_view['pagination'] = $select->getPagination();
        $this->_view['users'] = $select->getAll();

        $this->_view['current_user'] = $cur_user;

        if($select->getCount() > 10)
        {
            $this->_view['num'] = 10;
        }
        else
        {
            $this->_view['num'] = $select->getCount();
        }

        $this->_viewname = 'onlineuser';
    }

    function actionGetOnlineUser()
    {
        // 计算方法：
        // 如果用户上次登录的时间或者检查通知的时间比当前时间之间的差值少5分钟，则认为当前用户在线，否则用户不在线
        // 分页查询
        if(null == $this->_app->currentUser())
        {
            return $this->_redirect(url('default/index'));
        }
        $cur_user = $this->_app->currentUserObject();
        if($cur_user->permission_id != 2)
        {
            return $this->_redirect(url('default/index'));
        }
        
        $time = intval(CURRENT_TIMESTAMP);
        $last_check_time = $time - Q::ini('appini/web_intervel_check_time')*60;//比last_check_time大的才为登录用户

        $page = intval($this->_context->page);
        if ($page < 1) $page = 1;
        $user_num=0;
        $select = User::find('enterprise_id = ? AND last_check_time > ?', $cur_user->enterprise_id, $last_check_time)->all();
        $select->limitPage($page, 10);
        // 将分页信息和查询到的数据传递到视图
        $this->_view['pagination'] = $select->getPagination();
        $this->_view['users'] = $select->getAll();

        $this->_view['current_user'] = $cur_user;

        if($select->getCount() > 10)
        {
            $this->_view['num'] = 10;
        }
        else
        {
            $this->_view['num'] = $select->getCount();
        }

        $this->_viewname = 'onlineuser';
    }

    function actionPhoneLogin()
    {
        //..
        $login_result=0;
        $user = 0;

        if(!isset($this->_context->username) || !isset($this->_context->password))
        {
            $login_result=0;
        }
        else
        {
            $username = $this->_context->username;
            $passwd = $this->_context->password;
            try
            {
                $user = User::meta()->validateLogin($username, $passwd);
                $login_result=1;
                $this->_app->changeCurrentUser($user->aclData(), 'MEMBER');
            }
            catch (AclUser_UsernameNotFoundException $ex)
            {
                $login_result=0;
            }
            catch (AclUser_WrongPasswordException $ex)
            {
                $login_result=0;
            }
        }

        if($login_result == 1)
        {
            //增加是不是重新登录
            $now_time = intval(CURRENT_TIMESTAMP);// date();
            $isrelogin = (($now_time - $user->last_check_time) < 120)? true : false;//如果现在时间比上次检查时小于2分钟，则认为重新登录

            require 'genrss.php';

            $user->last_login_time = intval(CURRENT_TIMESTAMP);// date();
            $user->last_check_time = $user->last_login_time;//
            $user->login_count++;
            //$user->user_status  = 2;//表示用户通过客户端登录了
            //看到这个user_status只有这里使用，暂时注释掉，以后要是用的时候再调整
            $user->save();        

            $rss_gen=new RSS('电信', "http://www.baidu.com", '测试数据这里', '');

            $date = Date('Y-m-d H:i:s', time()); 
            $columns = Column::find('enterprise_id = ?', $user->enterprise_id)->order('column_sequence ASC')->getAll();
            $web_site=Q::ini('appini/web_site_ip');
            foreach($columns as $col)
            {
                //$column_site = $web_site;
                //$column_site .= 'index.php?controller=column&amp;action=require&amp;column_id='.$col->column_id;
                $column_id=$col->column_id;
                if(strlen($col->column_logo)> 3)
                {
                    $rss_gen->AddItem($col->column_name, $column_id, $web_site.$col->column_logo, $date, 'null');
                }
                else
                {
                    $rss_gen->AddItem($col->column_name, $column_id, 'null', $date, 'null');
                }			
            }  
            return $rss_gen->Display();
        }
        else
        {
            return "failed";
        }
    }


    function actionPhoneMEIDLogin()
    {
        //..
        $login_result=0;
        $user = 0;
        $clientVer = 0;
        if(isset($this->_context->ver))
        {
            $clientVer = $this->_context->ver;
        }

        if(!isset($this->_context->meid))
        {
            $login_result=0;
        }
        else
        {
            $meid = $this->_context->meid;
            $user = null;
            if(isset($this->_context->password))
            {
                $passwd = $this->_context->password;
                //$user = User::find('user_phone_meid = ? AND password = ?', $meid, $passwd)->query();
                //$user = User::find('user_phone_meid = ?', $meid)->query();
                //数据库更新后还是提示找不到user_phone_meid属性，先用user_email字段代替meid
                $user = User::find('user_email = ?', $meid)->query();
            }
            else
            {
                $user = User::find('user_email = ?', $meid)->query();
            }
            if ($user == null || 
                !isset($user->user_email) || 
                (isset($user->user_email) && trim($user->user_email) != $meid) )
            {
                //echo 'medi:'.$meid;
                $login_result=0;
            }
            else
            {
                $login_result=1;
            }
        }

        if($login_result == 1)
        {
            //增加是不是重新登录
            $now_time = intval(CURRENT_TIMESTAMP);// date();
            $isrelogin = (($now_time - $user->last_check_time) < 120)? true : false;//如果现在时间比上次检查时小于2分钟，则认为重新登录

            require 'genrss.php';

            $user->last_login_time = intval(CURRENT_TIMESTAMP);// date();
            $user->last_check_time = $user->last_login_time;//
            $user->login_count++;
            //$user->user_status  = 2;//表示用户通过客户端登录了
            //看到这个user_status只有这里使用，暂时注释掉，以后要是用的时候再调整
            $user->save();        
            $verInfo = $this->checkUpdate($clientVer, $user->enterprise_id);
            $forceUpdate = 0;
            $newApk = 0;
            if(!$verInfo['retCode'])
            {
                if(isset($verInfo['force']) && ($verInfo['force'] == 1 ))
                {
                    $forceUpdate = 1;
                    $newApk = $verInfo['info'];
                }
            }

            $rss_gen=new RSS("$forceUpdate", "$newApk,$user->enterprise_id", '测试数据这里', '');

            $date = Date('Y-m-d H:i:s', time()); 
            $columns = Column::find('enterprise_id = ?', $user->enterprise_id)->order('column_sequence ASC')->getAll();
            $web_site=Q::ini('appini/web_site_ip');
            foreach($columns as $col)
            {
                //$column_site = $web_site;
                //$column_site .= 'index.php?controller=column&amp;action=require&amp;column_id='.$col->column_id;
                $column_id=$col->column_id;
                if(strlen($col->column_logo)> 3)
                {
                    $rss_gen->AddItem($col->column_name, $column_id, $web_site.$col->column_logo, $date, 'null');
                }
                else
                {
                    $rss_gen->AddItem($col->column_name, $column_id, 'null', $date, 'null');
                }			
            }  
            return $rss_gen->Display();
        }
        else
        {
            return "failed";
        }
    }

    function actionlogin()
    {		
        if(null != $this->_app->currentUser())
        {
            return $this->_redirect(url('default/index'));
        }

        // 构造表单对象
        $form = new Form_Userlogin(url('user/login')); 
        if ($this->_context->isPOST())
        {
            //....
            try
            {
                //$_POST['username']
                $user = User::meta()->validateLogin($_POST['username'], $_POST['password']);

                if($user->permission_id == 4)
                {
                    return $this->_redirectMessage(
                        '友情提示您:',
                        "您输入的用户名 {$_POST['username']} 为普通用户，不能登录web管理端，请使用管理员用户登录",
                        url('default/index'));
                }
                // 将登录用户的信息存入 SESSION，以便应用程序记住用户的登录状态
                $this->_app->changeCurrentUser($user->aclData(), 'MEMBER');
                return $this->_redirect(url('default/index'));
            }
            catch (AclUser_UsernameNotFoundException $ex)
            {
                return $this->_redirectMessage(
                    '提示您:',
                    "您输入的用户名 {$_POST['username']} 不存在",
                    url('User/Login'));
                //$form['username']->invalidate("您输入的用户名 {$form['username']->value} 不存在");
            }
            catch (AclUser_WrongPasswordException $ex)
            {
                return $this->_redirectMessage(
                    '提示您:',
                    '您输入的密码不正确',
                    url('User/Login'));
                //$form['password']->invalidate("您输入的密码不正确");
            }
        }

        // 将表单对象传递给视图
        $this->_view['form'] = $form;
        $this->_view['open_reg_or_not']=Q::ini('appini/web_open_reg');
        $this->_viewname = 'login';
    }

    function actionChangePass()
    {
        if(!isset($this->_context->user_name))
        {
            echo "failed:0";//没有输入用户名
            return;
        }

        $username = $this->_context->user_name;

        //dump($username);
        if(!isset($this->_context->oldpass))
        {
            echo "failed:2";//没有输入新密码
            return;
        }

        if(!isset($this->_context->newpass))
        {
            echo "failed:3";//没有输入老密码
            return;
        }

        //dump($user);
        $oldpass = $this->_context->oldpass;

        //dump($oldpass);
        $newpassword = $this->_context->newpass;
        //dump($newpassword);
        try
        {
            $user = User::meta()->validateLogin($username, $oldpass);
        }
        catch (AclUser_UsernameNotFoundException $ex)
        {
            echo "failed:1";//用户不存在
            return;
        }
        catch (AclUser_WrongPasswordException $ex)
        {
            echo "failed:4";//老密码输入不正确
            return;
        }
        $user->password = $newpassword;
        $user->save();
        echo "success";
        return;
    }

    function actionregister()
    {		
        if(null != $this->_app->currentUser())
        {
            return $this->_redirect(url('default/index'));
        }

        // 构造表单对象
        $form = new Form_UserRegister(url('user/register')); 

        if ($this->_context->isPOST() && $form->validate($_POST))
        {
            // 是 POST 提交，并且表单验证通过
            try
            {
                // 创建 user 对象并保存
                $user = new User();

                $user->username=$form['username']->value;
                $user->password =$form['password']->value;
                $user->permission_id=1;
                $user->enterprise_id=1;
                $user->user_cellphone=0;
                $user->save();
                // 将登录用户的信息存入 SESSION，以便应用程序记住用户的登录状态
                $this->_app->changeCurrentUser($user->aclData(), 'MEMBER');
                return $this->_redirect(url('default/index'));
            }
            catch (AclUser_DuplicateUsernameException $ex)
            {
                // 捕获 AclUser_DuplicateUsernameException 异常，在表单中指出用户名存在重复问题
                $form['username']->invalidate("您要注册用户名 {$user->username} 已经存在了");
            }
        }

        // 将表单对象传递给视图
        $this->_view['form'] = $form;
        $this->_viewname = 'register';
    }

    function actionLogout()
    {
        if(null == $this->_app->currentUser())
        {
            return $this->_redirect(url('default/index'));
        }
        // 清除当前用户的登录信息
        $this->_app->quitCurrentUser();
        // 重定向浏览器
        return $this->_redirect(url('default/index'));
    }

    function actionSetting()
    {
        if(null == $this->_app->currentUser())
        {
            return $this->_redirect(url('default/index'));
        }

        $cur_user = $this->_app->currentUserObject();

        if(isset($_POST['password']))
        {
            $cur_user->password =$_POST['password'];
            $cur_user->reserved_2 = intval(CURRENT_TIMESTAMP);

            $cur_user->user_realname =$_POST['user_realname'];
            $cur_user->user_email =$_POST['user_email'];
            $cur_user->save();
            return $this->_redirectMessage(
                '提示您:',
                '用户设置完成',
                url('default/index'));
        }
        $this->_view['current_user'] = $cur_user;
        $this->_viewname = 'setting';
    }

    function actiontianyimanage()
    {
        if(null == $this->_app->currentUser())
        {
            return $this->_redirect(url('default/index'));
        }
        $cur_user = $this->_app->currentUserObject();
        if($cur_user->permission_id != 1)
        {
            return $this->_redirect(url('default/index'));
        }
        // 分页查询
        $page = intval($this->_context->page);
        if ($page < 1) $page = 1;
        $user_num=0;
        $select = User::find('permission_id = 1')->all();
        $select->limitPage($page, 10);
        // 将分页信息和查询到的数据传递到视图
        $this->_view['pagination'] = $select->getPagination();
        $this->_view['users'] = $select->getAll();

        $this->_view['current_user'] = $cur_user;

        if($select->getCount() > 10)
        {
            $this->_view['num'] = 10;
        }
        else
        {
            $this->_view['num'] = $select->getCount();
        }

        $this->_viewname = 'manage';
    }

    function actionManage()
    {
        if(null == $this->_app->currentUser())
        {
            return $this->_redirect(url('default/index'));
        }
        $cur_user = $this->_app->currentUserObject();

        // 分页查询
        $page = intval($this->_context->page);
        if ($page < 1) $page = 1;
        $user_num=0;

        if($cur_user->permission_id == 1 && $cur_user->enterprise_id == 1)
        {
            // 构造查询对象
            $user_permission_id = 2;//集团用户ID
            $select = User::find('permission_id = ?', $user_permission_id)->all();
            $select->limitPage($page, 10);
            // 将分页信息和查询到的数据传递到视图
            $this->_view['pagination'] = $select->getPagination();

            $this->_view['users'] = $select->getAll();
            if($select->getCount() > 10)
            {
                $this->_view['num'] = 10;
            }
            else
            {
                $this->_view['num'] = $select->getCount();
            }
        }
        else if($cur_user->permission_id == 2)
        {
            // 构造查询对象
            $ent_id = $cur_user->enterprise_id;
            $select = User::find('enterprise_id = ? AND permission_id <> 1 AND permission_id <> 2', $ent_id)->order('user_position ASC')->all();;
            $select->limitPage($page, 10);

            $this->_view['pagination'] = $select->getPagination();

            $this->_view['users'] = $select->getAll();

            // 将分页信息和查询到的数据传递到视图
            $user_num = $select->getCount();

            if($select->getCount() > 10)
            {
                $this->_view['num'] = 10;
            }
            else
            {
                $this->_view['num'] = $select->getCount();
            }
        }
        else
        {
            return $this->_redirect(url('default/index'));
        }   

        $this->_view['current_user'] = $cur_user;
        $this->_viewname = 'manage';
    }

    function actionContentManage()
    {
        if(null == $this->_app->currentUser())
        {
            return $this->_redirect(url('default/index'));
        }
        $cur_user = $this->_app->currentUserObject();

        // 分页查询
        $page = intval($this->_context->page);
        if ($page < 1) $page = 1;
        $user_num=0;

        if($cur_user->permission_id == 2)
        {
            // 构造查询对象
            $ent_id = $cur_user->enterprise_id;
            $select = User::find('enterprise_id = ? AND permission_id = 3', $ent_id)->all();;
            $select->limitPage($page, 10);

            $this->_view['pagination'] = $select->getPagination();

            $this->_view['users'] = $select->getAll();

            // 将分页信息和查询到的数据传递到视图
            $user_num = $select->getCount();

            if($select->getCount() > 10)
            {
                $this->_view['num'] = 10;
            }
            else
            {
                $this->_view['num'] = $select->getCount();
            }
        }
        else
        {
            return $this->_redirect(url('default/index'));
        }   

        $this->_view['current_user'] = $cur_user;
        $this->_viewname = 'manage';
    }

    function actionAddManager()
    {
        if(null == $this->_app->currentUser())
        {
            return $this->_redirect(url('default/index'));
        }
        $cur_user = $this->_app->currentUserObject();
        if(1 != $cur_user->permission_id)
        {
            return $this->_redirect(url('default/index'));
        }
        $this->_view['current_user'] = $cur_user;
        $this->_viewname = 'addmanager';
    }

    function actionAddMember()
    {
        if(null == $this->_app->currentUser())
        {
            return $this->_redirect(url('default/index'));
        }
        $cur_user = $this->_app->currentUserObject();

        if(isset($_POST['username'])){
            $cur_user = $this->_app->currentUserObject();
            //echo '$cur_user->id:'.$cur_user->id();
            try{
                // 创建 user 对象并保存
                $user = new User();

                $user->username=$_POST['username'];
                if(isset($_POST['userpasswd']))
                {
                    $user->password =$_POST['userpasswd'];
                }
                else
                {
                    $user->password =$_POST['username'];
                }

                if(isset($_POST['user_phone_meid']) && strlen($_POST['user_phone_meid']) > 0)
                {
                    $user->user_email=$_POST['user_phone_meid'];
                    $user->username=$_POST['user_phone_meid'];//如果用户输入了MEID，则把MEID作为用户名
                }

                if(1 != $cur_user->permission_id)
                {
                    $user->enterprise_id=$cur_user->enterprise_id;
                    $user->permission_id=$_POST['checktype'];
                }
                else
                {
                    if(isset($_POST['userenterprise']))
                    {
                        $user->enterprise_id=$_POST['userenterprise'];
                        if(isset($_POST['checktype']))
                        {
                            $user->permission_id=$_POST['checktype'];
                        }
                        else
                        {
                            $user->permission_id=2;//默认是企业管理员
                        }
                        
                        // reserved_1 用于记录用户初始密码设置时间
                        $user->reserved_2 = intval(CURRENT_TIMESTAMP);// date(); 
                    }
                    else
                    {
                        if(isset($_POST['checktype']))
                        {
                            $user->permission_id=$_POST['checktype'];
                        }
                        else
                        {
                            $user->permission_id=1;//默认是超级管理员
                        }
                        $user->enterprise_id=1;
                    }					    
                }
                if(isset($_POST['user_officetel']))
                {
                    $user->user_officetel=$_POST['user_officetel'];
                }
                
                if(isset($_POST['user_realname']))
                {
                    $user->user_realname=$_POST['user_realname'];
                }

                if(isset($_POST['user_work_position']))
                {
                    $user->reserved_1=$_POST['user_work_position'];//保留字段用来保存用户职位信息
                }
                else
                {
                    $user->reserved_1='职员';
                }
                
                $user->user_cellphone=$_POST['username'];
                $user->save();
                $dep = new Userindepartment();
                $dep->department_id = -1;
                if(isset($_POST['department_id']))
                {
                    $dep->department_id = $_POST['department_id'];
                }
                $dep->user_id = $user->id();//默认用户的部门为-1，属于整个公司
                $dep->save();
                if(isset($_POST['addflag']))
                {
                    return $this->_redirectMessage(
                    '提示您:',
                    '添加完成',
                    url('telephonebook/index'));
                }

                return $this->_redirectMessage(
                    '提示您:',
                    '添加完成',
                    url('User/manage'));
            }
            catch (AclUser_DuplicateUsernameException $ex)
            {
                // 捕获 AclUser_DuplicateUsernameException 异常，在表单中指出用户名存在重复问题
                return $this->_redirectMessage(
                    '提示您:',
                    '手机号码已经存在',
                    url('User/AddMember'));
            }
        }

        $select = Enterprise::find()->order('enterprise_id ASC')->all();
        $this->_view['enterprises'] = $select->getAll();
        $this->_view['enterprises_num'] = $select->getCount();

        //用户所在企业的部门
        if(2 == $cur_user->permission_id)
        {
            $deps = Department::find('enterprise_id = ?', $cur_user->enterprise_id)->all();
            $this->_view['deps'] = $deps->getAll();
        }

        $this->_view['current_user'] = $this->_app->currentUserObject();
        $this->_viewname = 'addmember';
    }


    function actionEdit()
    {
        if(null == $this->_app->currentUser())
        {
            return $this->_redirect(url('default/index'));
        }
        $edit_user = User::find('user_id = ?', $this->_context->user_id)->query();
        $cur_user = $this->_app->currentUserObject();

        //if($_POST['submitted'] == "yes")
        if(isset($_POST['user_realname']) && $this->_context->user_id == $edit_user->id())
        {
            $edit_user->user_realname=$_POST['user_realname'];
            if(isset($_POST['user_work_position']))
            {
                $edit_user->reserved_1 = $_POST['user_work_position'];
            }
            $edit_user->permission_id=$_POST['checktype'];
            if(isset($_POST['user_cellphone '])  && strlen($_POST['user_cellphone']) > 0)
            {
                $edit_user->user_cellphone=$_POST['user_cellphone'];
                $edit_user->username = $_POST['user_cellphone'];//用户名修改为新的电话号码
            }

            if(isset($_POST['user_officetel']) && strlen($_POST['user_officetel']) > 0)
            {
                $edit_user->user_officetel=$_POST['user_officetel'];
            }

            if(isset($_POST['user_phone_meid']) && strlen($_POST['user_phone_meid']) > 0)
            {
                $edit_user->user_email=$_POST['user_phone_meid'];

                $edit_user->username = $_POST['user_phone_meid'];//用户名修改为user_phone_meid
            }

            if(isset($_POST['client_visibility']) && $_POST['client_visibility'] == 'on')
            {
                $edit_user->user_status = -1;
            }
            else
            {
                $edit_user->user_status = 1;
            }
            
			try
			{
				$edit_user->save();
			}
            catch (AclUser_DuplicateUsernameException $ex)
            {
                // 捕获 AclUser_DuplicateUsernameException 异常
                return $this->_redirectMessage(
                    '提示您:',
					"您要注册用户的IMSI：{$user->username} 已经存在了",
                    url('User/eidt', array('user_id' => $edit_user->user_id)));
            }
			catch(QDB_Exception_DuplicateKey $ex)
			{
                // 捕获 AclUser_DuplicateUsernameException 异常
                return $this->_redirectMessage(
                    '提示您:',
				    "保存异常：IMSI重复",
                    url('User/edit', array('user_id' => $edit_user->user_id)));
			}
			catch(Exception $ex)
			{
                return $this->_redirectMessage(
                    '提示您:',
				    "保存异常",
                    url('User/edit', array('user_id' => $edit_user->user_id)));
			}

            try
            {
                $dep = Userindepartment::find('user_id = ?', $this->_context->user_id)->query();
                if($dep->user_id == $this->_context->user_id)
                {
                    $dep->department_id = $_POST['department_id'];
                    $dep->save();
                }
                else
                {					
                    $dep = new Userindepartment();
                    $dep->user_id = $edit_user->id();//默认用户的部门为-1，属于整个公司
                    if(isset($_POST['department_id']))
                    {
                        $dep->department_id = $_POST['department_id'];
                    }
                    $dep->save();
                }
            }
            catch(Exception $ex)
            {
                return $this->_redirect(url('user/manage'));
            }
            return $this->_redirect(url('user/manage'));
        }
        else if($this->_context->user_id == $edit_user->id())
        {
            //用户所在企业的部门
            $deps = Department::find('enterprise_id = ?', $cur_user->enterprise_id)->all();

            $dep = Userindepartment::find('user_id = ?', $this->_context->user_id)->query();
            $this->_view['dep_id'] = $dep->department_id;

            $this->_view['deps'] = $deps->getAll();

            $this->_view['depsCount'] = $deps->getCount();
        }

        $this->_view['current_user'] = $cur_user;
        $this->_view['edit_user'] = $edit_user;
        $this->_viewname = 'edituser';
    }
    
    function actionDeleteItem()
    {
        if(null == $this->_app->currentUser())
        {
            return $this->_redirect(url('default/index'));
        }
        $cur_user = $this->_app->currentUserObject();
        if(1 != $cur_user->permission_id && 2 != $cur_user->permission_id)
        {
            return $this->_redirect(url('default/index'));
        }

        User::meta()->destroyWhere('user_id = ?', $this->_context->user_id);

        //用户关联的数据是否删除
        return $this->_redirectMessage(
            '提示您:',
            '用户删除完成',
            url('User/manage'));
    }

    function actionDelete()
    {
        if(null == $this->_app->currentUser())
        {
            return $this->_redirect(url('default/index'));
        }
        $cur_user = $this->_app->currentUserObject();
        if(1 != $cur_user->permission_id && 2 != $cur_user->permission_id)
        {
            return $this->_redirect(url('default/index'));
        }

        if(isset($_POST['checkboxid'])){
            $id=$_POST['checkboxid'];

            foreach ($id as $value)
            {

                User::meta()->destroyWhere('user_id = ?', $value);

                //用户关联的数据是否删除
            }        
            return $this->_redirectMessage(
                '提示您:',
                '用户删除完成',
                url('User/manage'));
        }
        return $this->_redirect(url('User/manage'));
    }

    function actionImportFromExcel()
    {
        if(null == $this->_app->currentUser())
        {
            return $this->_redirect(url('default/index'));
        }
        $current_user = $this->_app->currentUserObject();
        if($current_user->permission_id != 2)
        {
            return $this->_redirect(url('default/index'));
        }
        //dump($current_user);
        if(isset($_POST['uploadxls']) && strlen($_POST['uploadxls'])>0)
        {
            $upload_excel_file = $_SERVER['DOCUMENT_ROOT'] . $_POST['uploadxls'];
            //dump(url('user/PreviewBatchImport', array('upload_excel_file' => $upload_excel_file)));
            //return $this->_redirectMessage('提示',
            //    '正在生成预览结果',
            //    url('user/PreviewBatchImport', array('upload_excel_file' => $upload_excel_file)));
            return $this->_redirect(url('user/PreviewBatchImport', array('upload_excel_file' => $upload_excel_file)));
        }
        $this->_viewname = 'importFromExcel';
    }

    function validateUserArray($user_array, $userid_array, $user_deps)
    {
        $good_users = Array();
        $bad_users = Array();
        $duplicate_users = User::find("username in (?)", $userid_array)->getAll();
        $used_username = Array();
        $dep_names = Array();

        foreach($duplicate_users as $du)
        {
            array_push($used_username, $du->username);
        }
        $count = 0;
        foreach($user_array as $user)
        {
            if(in_array($user->username, $used_username))
            {
                $count++;
                continue;
            }

            if($user->username == null && $user->user_cellphone == null)
            {
                $count++;
                array_push($bad_users, $user);
            }
            else
            {
                array_push($dep_names, $user_deps[$count++]);
                array_push($good_users, $user);
            }
        } 
        
        $result = Array('good_users' => $good_users, 'bad_users' => $bad_users, 'duplicate_users' => $duplicate_users, 'dep_names' => $dep_names);

        return $result;
    }

    function actionPreviewBatchImport()
    {
        if(null == $this->_app->currentUser())
        {
            return $this->_redirect(url('default/index'));
        }
        $current_user = $this->_app->currentUserObject();
        if($current_user->permission_id != 2)
        {
            return $this->_redirect(url('default/index'));
        }

        if($this->_context->isPOST())
        {
            $content = $this->readExcelFile($_POST['upload_excel_file'], $current_user);
            $result = $this->validateUserArray($content['user_array'], $content['userid_array'], $content['user_deps']);
            $good_users = $result['good_users'];
            $count = 0;
            foreach($good_users as $user)
            {
                $user->save();
                //增加用户到部门信息表中
                if(strlen($result['dep_names'][$count]) > 0)
                {
                    $dep_query = Department::find('department_name = ?', $result['dep_names'][$count])->query();        
                    if(isset($dep_query->department_name) && $dep_query->department_name == $result['dep_names'][$count])
                    {
                        $dep = new Userindepartment();
                        $dep-> department_id = $dep_query->id();//默认用户的部门为-1，属于整个公司
                        $dep->user_id = $user->id();//默认用户的部门为-1，属于整个公司
                        $dep->save();
                    }
                    else
                    {
                        $dep = new Department();
                        $dep->department_name = $result['dep_names'][$count];
                        $dep->enterprise_id = $current_user->enterprise_id;
                        $dep->save();
                        $depinuser = new Userindepartment();
                        $depinuser->department_id = $dep->id();//默认用户的部门为-1，属于整个公司
                        $depinuser->user_id = $user->id();//默认用户的部门为-1，属于整个公司
                        $depinuser->save();
                    }
                }
                else
                {
                    $dep = new Userindepartment();
                    $dep->user_id = $user->id();//默认用户的部门为-1，属于整个公司
                    $dep->save();
                }
                $count++;
            }
            return $this->_redirect(url('user/manage'));
        }
        else
        { 
            $upload_excel_file = $this->_context->upload_excel_file;
            $content = $this->readExcelFile($upload_excel_file, $current_user);
            $result = $this->validateUserArray($content['user_array'], $content['userid_array'], $content['user_deps']);
            $this->_viewname = 'previewbatchimport';
            $this->_view['good_users'] = $result['good_users'];
            $this->_view['bad_users'] = $result['bad_users'];
            $this->_view['duplicate_users'] = $result['duplicate_users'];
            $this->_view['user_dep'] = $result['dep_names'];
            $this->_view['bad_lines'] = 0;
            $this->_view['upload_excel_file'] = $upload_excel_file;
            $this->good_users = $result['good_users'];
        }
    }
    
    function readExcelFile($upload_excel_file, $current_user)
    {
        require_once '_code/lib/reader.php';

        // ExcelFile($filename, $encoding);
        $data = new Spreadsheet_Excel_Reader();
        // Set output Encoding.
        $data->setOutputEncoding('UTF-8');
        $data->read($upload_excel_file);
        $user_array = Array();
        $userid_array = Array();
        $user_deps = Array();
        $bad_lines = Array();
        //dump($data);
        for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) 
        {
            //dump($data->sheets[0]['cells'][$i][$j]);
            if(!isset($data->sheets[0]['cells'][$i][4]))
            {
                array_push($bad_lines, $i);
                continue;
            }
            $new_user = new User();
            $new_user->username = $data->sheets[0]['cells'][$i][4];
            $new_user->password = $new_user->username;
            if (isset($data->sheets[0]['cells'][$i][1]))
            {
                $new_user->user_realname = $data->sheets[0]['cells'][$i][1];
            }
            else
            {
                $new_user->user_realname = "";
            }

            if(isset( $data->sheets[0]['cells'][$i][2]))
            {
                $new_user->user_email = $data->sheets[0]['cells'][$i][2];
            }

            if(isset( $data->sheets[0]['cells'][$i][3]))
            {
                $new_user->user_hometel = $data->sheets[0]['cells'][$i][3];
            }
            
            if(isset( $data->sheets[0]['cells'][$i][4]))
            {
                $new_user->user_cellphone = $data->sheets[0]['cells'][$i][4];
            }
            else
            {                
                return $this->_redirectMessage(
                '提示您:',
                '用户手机号码必须输入',
                url('user/importfromexcel'));
            }
            
            if(isset( $data->sheets[0]['cells'][$i][5]))
            {
                $new_user->user_officetel = $data->sheets[0]['cells'][$i][5];
            }

            if(isset( $data->sheets[0]['cells'][$i][6]))
            {
                $new_user->user_position = $data->sheets[0]['cells'][$i][6];
            }
            else
            {
                $new_user->user_position = 1;
            }


            if(isset($data->sheets[0]['cells'][$i][7]))
            {
                $user_dep_value = $data->sheets[0]['cells'][$i][7];
            }
            else
            {
                $user_dep_value = '';
            }

            if(isset($data->sheets[0]['cells'][$i][8]))
            {
                $new_user->reserved_1 = $data->sheets[0]['cells'][$i][8];
            }
            else
            {
                $new_user->reserved_1 = '职员';
            }
            
            if(isset($data->sheets[0]['cells'][$i][9]))
            {
                $new_user->user_email = $data->sheets[0]['cells'][$i][9];
                $new_user->username= $data->sheets[0]['cells'][$i][9];//如果用户输入了MEID，则把MEID作为用户名
            }
            else
            {
                $new_user->user_email = '0';
            }

            $new_user->enterprise_id = $current_user->enterprise_id;
            $new_user->permission_id = 4;
            array_push($userid_array, $new_user->username);
            array_push($user_array, $new_user);
            array_push($user_deps, $user_dep_value);
        }
        $result = Array('userid_array' => $userid_array, 'user_array' => $user_array, 'user_deps' => $user_deps);
        return $result;
    }

    function actionbatchadd()
    {
        if(null == $this->_app->currentUser())
        {
            return $this->_redirect(url('default/index'));
        }
        $cur_user = $this->_app->currentUserObject();
        if(2 != $cur_user->permission_id)
        {
            return $this->_redirect(url('default/index'));
        }
        if(isset($_POST['submitted']))
        {
            $id=$_POST['MyBatchTelphone'];

            foreach ($id as $value){
                User::meta()->destroyWhere('user_id = ?', $value);
                $temp_use = User::find('username = ?', $value)->query();
                if(isset($temp_use->username) && ($temp_use->username  == $value))
                {
                    continue;
                }
                $user = new User();
                $user->username=$value;
                $user->password =$value;
                $user->user_cellphone =$value;
                $user->enterprise_id=$cur_user->enterprise_id;
                $user->permission_id=4;

                $user->save();
                $dep = new Userindepartment();
                $dep->user_id = $user->id();//默认用户的部门为-1，属于整个公司
                $dep->save();

                //用户关联的数据是否删除
            }        
            return $this->_redirectMessage(
                '提示您:',
                '批量用户添加完成',
                url('User/manage'));
        }

        $this->_view['current_user'] = $cur_user;
        $this->_viewname = 'batchAddMember';
    }

    function actionBuildAllClient()
    {
        $username = $this->_context->username;
        $password = $this->_context->password;
        if($username != 'leo' || $password != 'buildtest')
        {
            echo "intruder!!!";
            return;
        }
        $doc_root = $_SERVER['DOCUMENT_ROOT']; 
        $tools_dir  = $doc_root . $this->_context->baseDir() . 'tools';
        $ret_val = 0;
        $output = 0;

        $cmd = "$tools_dir/buildall.sh";
        dump($cmd);
        exec($cmd, $output, $ret_val);
        dump($output);
        dump($ret_val);
    }

    function checkUpdate($version, $enterpriseId)
    {
        $retVal = Array();
        //get apk dir
        $doc_root = $_SERVER["DOCUMENT_ROOT"];
        $base_dir = $this->_context->baseDir();
        $client_dir = "$doc_root/$base_dir/apk/$enterpriseId/";

        //get file list
        $apk_pattern = "$client_dir/surf-platform-*.apk";
        $apk_list = glob($apk_pattern);

        if(!$apk_list)
        {
            $retVal['retCode'] = 1;
            $retVal['info'] = 'no apks found';
        }

        $version_array = Array();
        foreach($apk_list as $apk)
        {
            $filename_array = explode(".", $apk);
            $version_string_array = explode("-", $filename_array[0]);
            $version_string = $version_string_array[2];
            $version = intval($version_string);
            if(!$version)
            {
                continue;
            }
            array_push($version_array, $version);
        }

        if(!$version_array)
        {
            $retVal['retCode'] = 1;
            $retVal['info'] = 'no valid apks found';
        }

        rsort($version_array);

        $retVal['retCode'] = 0;
        $retVal['info'] = $version_array[0];
        $retVal['force'] = 0;

        $force_flag = "$client_dir/.$version_array[0]";

        if(file_exists($force_flag))
        {
            $retVal['force'] = 1;
        }

        return $retVal;
    }

    function actionRequestNewClient()
    {
        $username = $this->_context->username;
        $current_user = User::find('username = ?' , $username)->getOne();
        if(!$username)
        {
            echo "failed";
            return;
        }

        $client_dir = "";
        $env_client_dir = getenv('CLIENT_SRC_DIR');
        if($env_client_dir)
        {
            $client_dir = $env_client_dir;
        }
        else
        {
            $doc_root = $_SERVER["DOCUMENT_ROOT"];
            $base_dir = $this->_context->baseDir();
            $client_dir = "$doc_root/$base_dir/apk/$current_user->enterprise_id/";
        }

        $apk_pattern = "$client_dir/surf-platform-*.apk";
        $apk_list = glob($apk_pattern);
        if(!$apk_list)
        {
            echo "failed";
            return -1;
        }
        $version_array = Array();
        foreach($apk_list as $apk)
        {
            $filename_array = explode(".", $apk);
            $version_string_array = explode("-", $filename_array[0]);
            $version_string = $version_string_array[2];
            $version = intval($version_string);
            if(!$version)
            {
                continue;
            }
            array_push($version_array, $version);
        }
        if(!$version_array)
        {
            echo "failed";
            return -1;
        }
        rsort($version_array);
        //dump($version_array);
        echo "$version_array[0],$current_user->enterprise_id";
        return;
    }
}


